package com.zz.nondatain.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;

import com.zz.nondatain.R;
import com.zz.nondatain.view.activity.ActiveSignInActivity;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

/**
 * 定位服务 - 前台服务以持续获取位置信息
 */
public class LocationService extends Service {
    
    private static final String TAG = "LocationService";
    private static final int NOTIFICATION_ID = 1;
    private static final String CHANNEL_ID = "location_service_channel";
    
    private LocationManager locationManager;
    private LocationListener locationListener;
    private Handler handler;
    private static final long MIN_TIME_BW_UPDATES = 5000; // 5秒更新一次
    private static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10米
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "LocationService Created");
        createNotificationChannel();
        startForeground(NOTIFICATION_ID, createNotification());
        
        handler = new Handler(Looper.getMainLooper());
        initLocationManager();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "LocationService Started");
        
        // 开始获取位置
        startLocationUpdates();
        
        // 如果系统杀死服务，重启时会重新调用onStartCommand
        return START_STICKY;
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "LocationService Destroyed");
        
        // 停止位置更新
        stopLocationUpdates();
    }
    
    /**
     * 初始化位置管理器
     */
    private void initLocationManager() {
        try {
            locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            
            locationListener = new LocationListener() {
                @Override
                public void onLocationChanged(@NonNull Location location) {
                    // 获取到位置后发送广播
                    String address = getAddressFromLocation(location.getLatitude(), location.getLongitude());
                    sendLocationBroadcast(address);
                }
                
                @Override
                public void onStatusChanged(String provider, int status, Bundle extras) {
                }
                
                @Override
                public void onProviderEnabled(@NonNull String provider) {
                }
                
                @Override
                public void onProviderDisabled(@NonNull String provider) {
                    sendLocationBroadcast("位置服务已禁用，请开启GPS");
                }
            };
        } catch (Exception e) {
            Log.e(TAG, "Error initializing location manager: " + e.getMessage());
        }
    }
    
    /**
     * 开始位置更新
     */
    private void startLocationUpdates() {
        try {
            if (locationManager != null && locationListener != null) {
                // 判断GPS是否可用
                boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                // 判断网络定位是否可用
                boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
                
                if (!isGPSEnabled && !isNetworkEnabled) {
                    sendLocationBroadcast("无法获取位置信息，请开启位置服务");
                    return;
                }


                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES,
                            locationListener
                    );
                    Log.d(TAG, "Network location updates started");
                }

                if (isGPSEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES,
                            locationListener
                    );
                    Log.d(TAG, "GPS location updates started");
                }

            }
        } catch (SecurityException e) {
            Log.e(TAG, "Error starting location updates: " + e.getMessage());
            sendLocationBroadcast("未获得定位权限");
        } catch (Exception e) {
            Log.e(TAG, "Error: " + e.getMessage());
            sendLocationBroadcast("位置服务发生错误");
        }
    }
    
    /**
     * 停止位置更新
     */
    private void stopLocationUpdates() {
        if (locationManager != null && locationListener != null) {
            try {
                locationManager.removeUpdates(locationListener);
                Log.d(TAG, "Location updates stopped");
            } catch (SecurityException e) {
                Log.e(TAG, "Error stopping location updates: " + e.getMessage());
            }
        }
    }
    
    /**
     * 发送位置信息广播
     */
    private void sendLocationBroadcast(String location) {
        Intent intent = new Intent("com.zz.nondatain.LOCATION_UPDATE");
        intent.putExtra("location", location);
        sendBroadcast(intent);
        Log.d(TAG, "Location broadcast sent: " + location);
    }

    /**
     * 创建通知渠道
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "Location Service Channel",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("位置服务正在后台运行");
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
    
    /**
     * 创建前台服务通知
     */
    private Notification createNotification() {
        Intent notificationIntent = new Intent(this, ActiveSignInActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this,
                0,
                notificationIntent,
                PendingIntent.FLAG_IMMUTABLE
        );
        
        return new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("位置服务")
                .setContentText("正在获取位置信息")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setContentIntent(pendingIntent)
                .setPriority(NotificationCompat.PRIORITY_LOW)
                .build();
    }

    /**
     * 将经纬度转换为具体地址
     * @param latitude 纬度
     * @param longitude 经度
     * @return 格式化的地址字符串
     */
    private String getAddressFromLocation(double latitude, double longitude) {
        try {
            android.location.Geocoder geocoder = new android.location.Geocoder(this, Locale.getDefault());
            List<android.location.Address> addresses = geocoder.getFromLocation(latitude, longitude, 1);
            
            if (addresses != null && !addresses.isEmpty()) {
                android.location.Address address = addresses.get(0);
                StringBuilder sb = new StringBuilder();
                
                // 国家
//                if (address.getCountryName() != null) {
//                    sb.append(address.getCountryName());
//                }
                
                // 省/州
//                if (address.getAdminArea() != null) {
//                    sb.append(address.getAdminArea());
//                }
                
                // 城市
                if (address.getLocality() != null) {
                    sb.append(address.getLocality());
                }
                
                // 区/县
                if (address.getSubLocality() != null) {
                    sb.append(address.getSubLocality());
                }
                
                // 街道/路
                if (address.getThoroughfare() != null) {
                    sb.append(address.getThoroughfare());
                }
                
                // 门牌号
                if (address.getSubThoroughfare() != null) {
                    sb.append(address.getSubThoroughfare());
                }
                
                // 详细信息，例如建筑名称等
                if (address.getFeatureName() != null && 
                    !address.getFeatureName().equals(address.getSubThoroughfare())) {
                    sb.append(address.getFeatureName());
                }
                
                // 如果地址解析成功但长度为0，则可能是因为某些地区的地址信息不完整
                if (sb.length() == 0) {
                    return "西部智谷"; // 默认地址
                }
                
                return sb.toString();
            }
        } catch (IOException e) {
            Log.e(TAG, "Error getting address: " + e.getMessage());
        }
        
        // 如果地址解析失败，返回默认地址
        return "中国成都市武侯区武兴五路433号2栋西部智谷";
    }
} 